package net.wanho.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.crypto.SecureUtil;
import com.wf.captcha.ArithmeticCaptcha;
import com.wf.captcha.base.Captcha;
import lombok.RequiredArgsConstructor;
import net.wanho.constant.CaptchaConstant;
import net.wanho.constant.UserConstant;
import net.wanho.dto.LoginDTO;
import net.wanho.exception.UnauthorizedException;
import net.wanho.po.UserInfo;
import net.wanho.service.CaptchaService;
import net.wanho.service.UserInfoService;
import net.wanho.util.JwtUtil;
import net.wanho.vo.CaptchaVo;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
@RequiredArgsConstructor
public class CaptchaServiceImpl implements CaptchaService {

    private final StringRedisTemplate redisTemplate;

    private final UserInfoService userInfoService;

    @Override
    public CaptchaVo captcha() {
        Captcha captcha = new ArithmeticCaptcha();
        System.out.println(captcha.text());

        String base64 = captcha.toBase64();

        String uuid = UUID.randomUUID().toString();
        System.out.println(uuid);

        redisTemplate.opsForValue().set(CaptchaConstant.CAPTCHA_PREFIX + uuid, captcha.text(),CaptchaConstant.CAPTCHA_EXPIRE, TimeUnit.MINUTES);

        return new CaptchaVo(uuid, base64);
    }

    @Override
    public String login(LoginDTO loginDTO) {
        String uuid =CaptchaConstant.CAPTCHA_PREFIX + loginDTO.getUuid();
        String code = redisTemplate.opsForValue().get(uuid);
        System.out.println(code);
        if (ObjectUtil.isEmpty(code)){
            throw new UnauthorizedException("验证码已过期");
        }
        redisTemplate.delete(uuid);
        //验证码验证忽略大小写
        if (!code.equalsIgnoreCase(loginDTO.getCode())){
            throw new UnauthorizedException("验证码错误");
        }

        UserInfo userInfo = userInfoService.findByName(loginDTO.getUserCode());

        if (userInfo == null){
            throw new UnauthorizedException("用户名不存在");
        }

        if(!userInfo.getUserPwd().equals(SecureUtil.md5(loginDTO.getUserPwd()))){
            throw new UnauthorizedException("密码错误");
        }
        if(userInfo.getUserState().equals(UserConstant.USER_DISABLE)){
            throw new UnauthorizedException("用户被禁用");
        }

        Map<String, Object> payload = new HashMap<>();
        payload.put(UserConstant.USER_ID, userInfo.getUserId());
        payload.put(UserConstant.USER_CODE, userInfo.getUserCode());
        String token ="Bearer " + JwtUtil.generate(payload);

        return token;
    }

    @Override
    public Boolean logout() {
        return true;
    }
}
